import _ from "lodash";
export const messageHandler = (messages: Message[]) => {
  let result = _.cloneDeep(messages);
  const first_mes = result.find((item) => item.identifier === "first_mes");
  result.push({ ...first_mes!, role: "assistant", type: "chat" });
  const history = messages.filter((item) => item.type === "chat");
  let historyLength = history.length;
  const newChat = history.pop();
  const lastAnswer = history.pop();
  const jailbreak = result.findIndex((item) => item.identifier === "jailbreak");
  newChat && jailbreak && result.splice(jailbreak, 0, newChat!);
  lastAnswer && jailbreak && result.splice(jailbreak - 1, 0, lastAnswer!);
  const chatHistoryIndex = result.findIndex(
    (item) => item.identifier === "chatHistory"
  );
  const startMessageIndex = result.findIndex(
    (item) => item.identifier === "new_chat_prompt"
  );
  startMessageIndex && historyLength++;
  startMessageIndex &&
    result.splice(chatHistoryIndex, 1, result[startMessageIndex]);
  chatHistoryIndex && result.splice(chatHistoryIndex + 1, 0, ...history);
  result.length = result.length - historyLength;
  return result.map((e) => {
    return { role: e.role, content: e?.content ?? "" };
  });
};
